package com.haixinga.commbiz.mgr.ctrl.anno;

import com.haixinga.commbiz.commons.biz.ITokenService;
import com.haixinga.commbiz.commons.entity.SysUser;
import com.haixinga.commbiz.commons.service.SysApiService;
import com.haixinga.commbiz.commons.service.SysRoleEntRelaService;
import com.haixinga.commbiz.commons.service.SysUserService;
import com.haixinga.commbiz.commons.vo.ApiRes;
import com.haixinga.commbiz.mgr.ctrl.CommonCtrl;
import com.haixinga.commbiz.mgr.vo.MgrLoginUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.haixinga.commbiz.commons.constants.CS;
import com.haixinga.commbiz.commons.exception.BizException;
import com.haixinga.commbiz.commons.utils.StringKit;


@RestController
@RequestMapping("anno/auth")
public class AuthController extends CommonCtrl {

	@Autowired private SysUserService sysUserService;
	@Autowired private SysRoleEntRelaService sysRoleEntRelaService;
	@Autowired private SysApiService sysApiService;


	/** 用户信息认证 获取iToken  **/
	@RequestMapping(value = "/validate", method = RequestMethod.POST)
	public ApiRes validate() throws BizException {


		String account = getValStringRequired("ia");  //用户名 i account, 已做base64处理
		String ipassport = getValStringRequired("ip");	//密码 i passport,  已做base64处理

		//我的通行证进行校验
		account = StringKit.base64Decode(account);  //转换为明文
		ipassport = StringKit.base64Decode(ipassport); //转换为明文

        SysUser user = sysUserService.accountValidate(account, ipassport);
		if(user == null){ //登录失败
			return ApiRes.customFail("用户名/密码有误！");
		}

		//设置缓存对象信息
		MgrLoginUserVO loginUserVO = new MgrLoginUserVO();
		loginUserVO.setUserId(user.getSysUserId());
		loginUserVO.setUsername(user.getRealname());
		loginUserVO.setSysUser(user);
		loginUserVO.setEntIdList(sysRoleEntRelaService.selectEntIdsByUserId(user.getSysUserId()));
		loginUserVO.setApiIdList(sysApiService.selectApiIdsByUserId(user.getSysUserId()));


		//生成iToken 并放置到缓存
		String iToken = StringKit.getUUID();  //TODO 1 更改为更安全的方式
		ITokenService.processTokenCache(loginUserVO, iToken); //处理token 缓存信息

		return ApiRes.ok4newJson(CS.ACCESS_TOKEN_NAME, iToken);
	}


}
